package com.tanhua.sso.service;

import cn.hutool.core.util.ObjectUtil;
import com.tanhua.common.pojo.User;
import com.tanhua.sso.vo.ErrorResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class MyCenterService {

    @Autowired
    private SmsService smsService;

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param token
     * @return
     */
    public boolean sendVerificationCode(String token) {

        //验证token
        User user = this.userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)){
            return false;
        }

        ErrorResult result = this.smsService.sendCheckCode(user.getMobile());

        return result == null;
    }

    /**
     * 校验验证码
     *
     * @param code
     * @param token
     * @return
     */
    public Boolean checkVerificationCode(String code, String token) {

        //验证token
        User user = this.userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)){
            return false;
        }

        //校验验证码,先查看Redis中的验证码
        String redisKey = "CHECK_CODE_" + user.getMobile();
        String value = this.redisTemplate.opsForValue().get(redisKey);

        if (ObjectUtil.equal(code,value)){
            //将验证码删除
            this.redisTemplate.delete(redisKey);
            return true;
        }

        return false;
    }

    /**
     * 保存新手机号
     *
     * @param token
     * @param newPhone
     * @return
     */
    public boolean updatePhone(String token, String newPhone) {

        //验证token
        User user = this.userService.queryUserByToken(token);
        if (ObjectUtil.isEmpty(user)){
            return false;
        }

        //保存新手机号
        Boolean result = this.userService.updatePhone(user.getId(), newPhone);

        return false;
    }
}
